package cn.zmwh.im.server.netty;


import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserChannelMap {

    /**
     * 维护userId和ctx的关联关系，格式:Map<userId,map<terminal，ctx>>
     */
    private static Map<Long, Map<String, Channel>> channelMap = new ConcurrentHashMap();

    public static void addChannel(Long uid, String terminal, Channel channel) {
        channelMap.computeIfAbsent(uid, key -> new ConcurrentHashMap()).put(terminal, channel);
    }

    public static void removeChannel(Long uid, String terminal) {
        if (uid != null && terminal != null && channelMap.containsKey(uid)) {
            Map<String, Channel> userChannelMap = channelMap.get(uid);
            userChannelMap.remove(terminal);
            if (userChannelMap.isEmpty()) {
                channelMap.remove(uid);
            }
        }
    }

    public static Channel getChannel(Long uid, String terminal) {
        if (uid != null && StrUtil.isNotEmpty(terminal) && channelMap.containsKey(uid)) {
            Map<String, Channel> userChannelMap = channelMap.get(uid);
            if (userChannelMap.containsKey(terminal)) {
                return userChannelMap.get(terminal);
            }
        }
        return null;
    }

    public static Map<String, Channel> getChannel(Long uid) {
        if (uid == null) {
            return null;
        }
        return channelMap.get(uid);
    }

}
